package com.xy.breakfast.controller;

import com.xy.breakfast.entity.*;
import com.xy.breakfast.service.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

@Controller
public class CartController {
    @Autowired
    OrdersService ordersService;

    @Autowired
    ProductsService productsService;

    @Autowired
    CartService cartService;
    @Autowired
    ClientsService clientsService;
    @Autowired
    FoodsService foodsService;

    java.util.logging.Logger logger = Logger.getLogger(this.getClass().getName());

    //把食品加入购物车
    @RequestMapping("/saveCart")
    @ResponseBody
    public String save(@RequestBody Map<String,String> maps, HttpServletRequest request){
        logger.info("客户开始添加购物车食品...");

        //判断客户登录状态
        Clients clients=(Clients) request.getSession().getAttribute("clients");
        if(clients==null) return "客户未登录";

        //获取下单的参数
        int clientsId=clients.getId();
        logger.info("ccccccc"+clientsId);
        int foodsId=Integer.parseInt(maps.get("foodsId"));

//        int num=Integer.parseInt(maps.get("num"));
        //创建购物车
        Cart cart=new Cart();
        cart.setClientsId(clientsId);
        cart.setFoodsId(foodsId);
        cart.setNum(1);
        cart.setPrice(foodsService.getById(foodsId).getPrice());
        cart.setCreateTime(new Timestamp(System.currentTimeMillis()));

        cartService.save(cart);
        logger.info("添加成功");

        return "ok";

    }


    //获取用户的购物车
    @RequestMapping("/getCartByClientId")
    @ResponseBody
    public List<Cart> getCartByClientId(HttpServletRequest request){
        //获取登录用户编号
        Clients clients=(Clients) request.getSession().getAttribute("clients");
        if(clients==null) return null;

        //查询这个用户的购物车记录
        List<Cart> cartList=cartService.getByClientsId(clients.getId());

        //设置购物车外键的关联实体
        for (Cart cart:cartList){
            cart.setClients(clientsService.getById(cart.getClientsId()));
            cart.setFoods(foodsService.getById(cart.getFoodsId()));
        }

        return cartList;
    }

    //把食品移除购物车
    @RequestMapping("/deleteCart")
    @ResponseBody
    public String deleteCart(@RequestBody Map<String,String> maps,HttpServletRequest request){
        //获取要删除的购物车编号
        int id=Integer.valueOf(maps.get("id"));

        //判断客户登录的状态
        Clients clients=(Clients) request.getSession().getAttribute("clients");
        if(clients==null) return "客户未登录！";

        int clientsId=clients.getId();
        Cart cart=cartService.getById(id);

        if(cart==null) return "删除的购物车不存在";
        logger.info("bb:"+cart);
        logger.info("aa"+cart.getClientsId());
        logger.info("aa"+clients.getId());
        logger.info("cc"+clientsId);

        if(clientsId!=clients.getId()) return "你无法删除别人的购物车";

        cartService.deleteById(id);

        return "ok";
    }


    //客户购买下单功能
    @RequestMapping("/getCheckOut")
    @ResponseBody
    @Transactional //数据库事务保证操作一定成功
    public String getCheckOut(@RequestBody Map<String,String >maps, HttpServletRequest request) throws ParseException {
        logger.info("客户立即下单..."+new Date(System.currentTimeMillis()));

        Clients clients=(Clients) request.getSession().getAttribute("clients");

        if(clients==null) return "客户未登录，不能下单";

        //获取下单的参数
        int clientsId=clients.getId();

        List<Cart> cartList=cartService.getByClientsId(clientsId);

        String dateString = String.valueOf(maps.get("takeTime"));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = formatter.parse(dateString);
        Timestamp timestamp = new Timestamp(date1.getTime());
        logger.info("时间"+timestamp);
        int isPack=Integer.parseInt(maps.get("isPack"));
        String phone=maps.get("phone");
        String address=maps.get("address");
        int payMethod=Integer.valueOf(maps.get("payMethod"));
        if(address.trim().length()==0) return "请填写收货地址！";
        if(phone.trim().length()==0)return "请填写电话！";

        int state=0; //未制作

        for(Cart cart:cartList){
            int foodsId=cart.getFoodsId();
            int num=cart.getNum();
            BigDecimal price=cart.getPrice();
            Timestamp createTime=cart.getCreateTime();

            //设置订单内容
            Foods foods=foodsService.getById(foodsId);

            //判断库存
            if(foods.getNum()<num) return "食品库存不足";

            //创建订单
            Orders orders=new Orders();
            orders.setClientsId(clientsId);
            orders.setFoodsId(foodsId);
            orders.setNum(num);
            orders.setPrice(price);
            orders.setCreateTime(new Timestamp(System.currentTimeMillis()));
            orders.setTakeTime(timestamp);
            orders.setIsPack((byte)isPack);
            orders.setPhone(phone);
            orders.setAddress(address);
            orders.setPayMethod(payMethod);

            //创建制作
            Products products=new Products();
            products.setOrdersId(-1);
            products.setTakeTime(timestamp);
            products.setIsPack((byte)isPack);
            products.setAddress(address);
            products.setState(state);
            //保存订单和制作
            ordersService.save(orders);
            products.setOrdersId(orders.getId());
            productsService.save(products);
            //更新食品库存减少
            foods.setNum(foods.getNum()-num);
            foodsService.update(foods);

        }
        for(Cart cart:cartList) {
            cartService.deleteById(cart.getId());
        }
        return "ok";
    }

    @RequestMapping("/updateCart")
    @ResponseBody
    public String updateCart(@RequestBody Map<String, Object> maps, HttpServletRequest request) {

        // 检查用户是否登录
        Clients client = (Clients) request.getSession().getAttribute("clients");
        if (client == null) {
            return "客户未登录";
        }

        Integer cartId = (Integer) maps.get("id");
        Integer num = (Integer) maps.get("num");
        Integer foodsId=(Integer)maps.get("foodsId");

        Cart cart = cartService.getById(cartId);
        Foods food = foodsService.getById(foodsId);


        BigDecimal price = food.getPrice().multiply(BigDecimal.valueOf(num));


        // 检查库存

        List<Cart> cartList=cartService.getByClientsId(cartId);


        // 更新购物车数量和总价
        cart.setNum(num);
        cart.setPrice(price);

        // 更新数据库
        cartService.update(cart);

        return "ok";

        //        logger.info("aa"+cart.getClientsId());
//        logger.info("cc"+client.getId());
//        // 检查用户是否有权限修改该购物车条目
//        if (cart.getClientsId()!=client.getId()) {
//            return "无权修改他人的购物车";
//        }
//
//        Foods food = foodsService.getById(cart.getFoodsId());
//
//        // 检查 foodsId 是否正确
//        int foodsId = cart.getFoodsId();
//        logger.info("vv"+foodsId);
//        logger.info("aad"+cart.getFoods().getId());
//        if (foodsId != cart.getFoods().getId()) {
//            // 输出错误信息
//            logger.info("cart.getFoodsId() 获取的数据不准确");
//            // 返回错误信息或进行其他处理
//        }
//        logger.info("ff"+food);
//        logger.info("cc"+food.getNum());
//        logger.info("dd"+num);
//        if (food == null || food.getNum() < num) {
//            return "库存不足";
//        }

//        BigDecimal newPrice = food.getPrice().multiply(BigDecimal.valueOf(num));
//        cart.setPrice(newPrice);
    }

}
